<template>
  <input class="uploadFile" type="file" ref="fileInput" @change="uploadFile($event.target)" multiple>
</template>
<script>
import { mapGetters, mapMutations, mapActions } from 'vuex'
import { fammterString } from '@/api/library_upload/upload'
import { realuploadFile } from '@/api/library_index'
import { realuploadGroupFile } from '@/api/library_groupList/groupList'

export default {
  data() {
    return {}
  },
  props: {
    map: {
      type: String,
      required: false
    },
    groupId: {
      type: Number,
      required: false
    }
  },
  computed: {
    ...mapGetters('libraryFile', ['pathArr'])
  },
  methods: {
    ...mapMutations('uploadList', ['addUploadItem', 'updateUploadStatus', 'removeUploadItem', 'changeProgress']),
    ...mapActions('uploadList', ['addArrItem', 'requestUpload', 'uploadCheck']),
    clickInput() {
      this.$refs.fileInput.click()
    },
    async uploadFile(event) {
      const file = this.$refs.fileInput.files
      if (!file) {
        return
      }
      let filePath = `${this.pathArr[this.pathArr.length - 1].filePath}${this.pathArr[this.pathArr.length - 1].filePath == '/' ? '' : '/'}${this.pathArr[this.pathArr.length - 1].fileName || ''}`
      let parentId = this.pathArr[this.pathArr.length - 1].id
      let arr = []
      for (let e of file) {
        arr.push({
          id : await this.addArrItem(e),
          file:e
        })
      }
      let that = this
      async function upload(e) {
          that.uploadCheck({
            id: e.id,
            file: e.file,
            event,
            filePath,
            parentId,
            map: that.map,
            groupId: that.groupId
          }).then(bol=>{
            if (bol.code == 200) {
              if (bol.data.uploadFileList.length != 0) {
                let arr = []
                let fileList = Array.from(e.file)
                bol.data.uploadFileList.forEach(item => {
                  fileList.forEach(fileItem => {
                    if (fileItem.fileName + '.' + fileItem.extendName == item.name) {
                      arr.push(fileItem)
                    }
                  })
                })
                that.uploadFiles(e.id, event, e.file, filePath, parentId, that.map, that.groupId)
              } else {
                // TODO 直接改变上传列表对应项状态为成功
                that.updateUploadStatus({ id: e.id, status: 2 })
                that.changeProgress({ id: e.id, progress: 100 })
                that.removeUploadItem(e.id)
                that.$message({
                  type: 'success',
                  message: '上传成功!'
                })
                that.refreshList()
              }
            } else {
            }
          }).catch(err=>{
            console.log(err)
            console.log('111111')
            // TODO 方法一：空间不足时将上传列表对应项删除
            // TODO 方法二：空间不足时将上传列表对应项改为失败状态
            // that.updateUploadStatus({ id: e.id, status: 3 })
            that.removeUploadItem(e.id)
          })

      }
      arr.forEach(item=>{
        upload(item)
      })
      // 重置
      event.value = ''
    },
    uploadFiles(id, event, file, filePath, parentId, map, groupId) {
      try {
        let path = fammterString(`${map ? map : 'user'}`, groupId)
        // TODO 将uploadOSS方法替换为requestUpload方法，并多穿入一个id参数
        this.requestUpload({ file, path, id }).then(res => {
          // 上传资源库
          this.uploadreal(res, parentId, filePath, groupId)
        })
        // uploadOSS(file, path).then(res => {
        //   // 上传资源库
        //   this.uploadreal(res, parentId, filePath, groupId)
        // }).catch(err => {
        //   console.log(err)
        // })
      } catch (e) {
        this.$message.error('上传失败，请重新选择文件进行上传')
      }
    },
    // 上传
    async uploadreal(arr, parentId, filePath, groupId) {
      arr.map(item => {
        item.parentId = parentId
        item.filePath = filePath
      })
      let res
      if (groupId) {
        res = await realuploadGroupFile({
          uploadFileList: arr,
          parentId: parentId,
          filePath: filePath,
          groupId: this.groupId
        })
      } else {
        res = await realuploadFile({ uploadFileList: arr, parentId: parentId, filePath: filePath })
      }

      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '上传成功!'
        })
        this.refreshList()
      }
    },
    refreshList() {
      this.$emit('refreshList')
    }
  }
}

</script>
<style scoped lang="scss">
.uploadFile {
  display: none;
}
</style>
